package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.context.SessionConstants;
import cn.livingCloud.dto.CaseFinishFormDto;
import cn.livingCloud.dto.CaseImageDto;
import cn.livingCloud.dto.JsonDto;
import cn.livingCloud.entity.core.CaseImage;
import cn.livingCloud.entity.core.CaseStatus;
import cn.livingCloud.entity.core.Employee;
import cn.livingCloud.entity.core.EmployeeWechat;
import cn.livingCloud.repository.CaseImageMapper;
import cn.livingCloud.repository.EmployeeWechatMapper;
import cn.livingCloud.utils.SessionUtils;

import java.util.List;

/**
 * Created by DingJie on 2016/6/7.
 */
public class CaseFinisher extends CaseOperator {
    protected transient CaseImageMapper caseImageMapper = BeanProvider.getBean(CaseImageMapper.class);
    protected transient EmployeeWechatMapper employeeWechatMapper = BeanProvider.getBean(EmployeeWechatMapper.class);
    private CaseFinishFormDto formDto;

    public CaseFinisher() {
    }

    public CaseFinisher(CaseFinishFormDto formDto) {
        super(formDto);
        this.formDto = formDto;
    }

    @Override
    protected JsonDto operation() {
        saveImage(formDto);
        setCaseStatus();
        Employee attribute = SessionUtils.getAttribute(Employee.class, SessionConstants.EMPLOYEE_KEY);
        if (attribute != null) {
            super.aCase.setOwnerId(attribute.getUuid());
        }
        msgService.sendFinishMsg(aCase);
        JsonDto jsonDto = new JsonDto();
        jsonDto.setState(true);
        return jsonDto;
    }

    /**
     * 1,体制内的人员创建的案件,完成不需要通过审核
     * 2,群众举报案件需要进行审核后才能归为已完成
     */
    private void setCaseStatus() {
        String creatorUuid = aCase.getCreatorUuid();
        List<EmployeeWechat> wechats = employeeWechatMapper.findByMemberUuid(creatorUuid);
        if (!wechats.isEmpty() || wechats.size() > 0) {
            super.aCase.setStatus(CaseStatus.FINISH);
        } else {
            super.aCase.setStatus(CaseStatus.PENDING);
        }
    }

    @Override
    protected List<Employee> getNewOwners() {
        return null;
    }

    public void saveImage(CaseFinishFormDto formDto) {
        List<CaseImageDto> imageList = formDto.getImageList();
        for (CaseImageDto caseImageDto : imageList) {
            CaseImage caseImage = new CaseImage().setIsResult(true).setCaseUuid(formDto.getCaseUuid()).setUrl(caseImageDto.getUrl());
            caseImageMapper.insert(caseImage);

            new CaseImageDownloadHandler(caseImage).handler();
        }
    }
}
